<template>
  <div>
    <a-modal title="确认出库" :visible="visible" @before-open="open" @cancel="handleCancel" :align-center="false" title-align="start" width="1200px" :mask-closable="false">
      <div class="table">
        <a-table class="table-two-line" ref="tableListref" style="width: 1160px" :summary="summary" :span-method="spanMethodAll" row-key="id" :expandable="expandable" :default-expand-all-rows="true" :bordered="false" :columns="tableColumns" :data="tableList" size="mini" :pagination="false" :scroll="{ y: '500px' }">
          <template #columns>
            <a-table-column v-for="(item, index) of tableColumns" :fixed="item.fixed" :key="index" :align="item.align" :width="item.width" :title="item.title" :data-index="item.dataIndex">
              <template v-if="item.dataIndex == 'img'" #cell="{ record }">
                <!-- <div class="flex-c-sb" style="display: flex; align-items: center"> -->
                <div style="display: flex; align-items: center">
                  <div class="order-w flex">
                    <p>
                      <span class="label">交货单号：</span>
                      <span>{{ record.billNo }}</span>
                    </p>
                    <p style="margin: 0 20px">
                      <span class="label">经销商：</span>
                      <span>{{ record.companyName }}</span>
                    </p>
                    <p>
                      <span class="label"> 交货仓：</span>
                      <span>{{ record.deliveryWarehouseName }}({{ record.deliveryWarehouseCode }})</span>
                    </p>
                    <p style="margin: 0 20px">
                      <span class="label"> 物流方式：</span>
                      <span>{{ record.logisticType == '1' ? '线下配送' : '快递' }}</span>
                    </p>
                    <p>
                      <span class="label"> 物流跟踪号：</span>
                      <span>{{ record.logisticName }}/{{ record.logisticsTrackNumber }}</span>
                    </p>
                  </div>
                </div>
              </template>
            </a-table-column>
          </template>
          <template #expand-row="{ record }">
            <a-table class="table-singe-line" row-class="child-row" v-model:selected-keys="ids" :row-selection="rowSelection" :show-header="false" row-key="id" :bordered="false" :columns="tableColumns" :data="record.billItems" size="mini" :pagination="false">
              <template #columns>
                <a-table-column v-for="(item, index) of tableColumns" :key="index" :fixed="item.fixed" :align="item.align" :width="item.width" :title="item.title" :data-index="item.dataIndex">
                  <template v-if="item.dataIndex == 'img'" #cell="option">
                    <ImgPopover :src="option.record.productImg">
                      <template #con>
                        <a-image width="40" height="40" fit="contain" :src="option.record.productImg" />
                      </template>
                    </ImgPopover>
                  </template>
                  <template v-else-if="item.dataIndex == 'productName'" #cell="option">
                    <TextLimit :rows="2" position="top">{{ option.record.productName }}</TextLimit>
                  </template>

                  <template v-else-if="item.dataIndex == 'sku'" #cell="option">
                    <TextLimit :rows="1">{{ option.record.sku || '--' }}</TextLimit>
                  </template>
                  <template v-else-if="item.dataIndex == 'ssku'" #cell="option">
                    <TextLimit :rows="1">{{ option.record.ssku || '--' }}</TextLimit>
                  </template>

                  <template v-else-if="item.dataIndex == 'gmtPlanDelivery'" #cell="option">
                    <div>{{ $setTime(option.record.gmtPlanDelivery, 'YYYY/MM/DD') }}</div>
                    <div v-if="option.record.gmtPlanDelivery">
                      <div style="color: red" v-if="!toCheckDay(option.record.gmtPlanDelivery).type">超时{{ toCheckDay(option.record.gmtPlanDelivery).day }}天</div>
                      <div class="highlight" v-else>剩余{{ toCheckDay(option.record.gmtPlanDelivery).day }}天</div>
                    </div>
                  </template>

                  <template v-else-if="item.dataIndex == 'rate'" #cell="option">
                    <TextLimit :rows="1">{{ option.record.rate }}%</TextLimit>
                  </template>
                  <template v-else-if="item.dataIndex == 'price'" #cell="option">
                    <TextLimit :rows="1">￥{{ option.record.price }}</TextLimit>
                  </template>
                </a-table-column>
              </template>
            </a-table>
          </template>
          <template #summary-cell="{ column, record, rowIndex }">
            <div>{{ record[column.dataIndex] }}</div>
          </template>
        </a-table>
      </div>

      <template #footer>
        <a-button class="gray-outline" @click="handleCancel">取消</a-button>
        <a-button type="primary" :loading="loading" class="ml10" @click="handleOk">确认出库</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, toRefs, computed } from 'vue'
  import { findWarehouseListByParam } from '@/api/warehouse'
  import { getSupplierDeliveryInfo, outboundSupplierDeliveryOrder } from '@/api/supplier'
  import { Message } from '@arco-design/web-vue'
  import _ from 'lodash-es'
  export default defineComponent({
    props: ['type', 'list'],
    setup(props: any, { emit }) {
      let visible = ref(false)
      const formRef = ref()
      const data: any = reactive({
        rules: [],
        form: {},
        houseList: [],
        itemList: [],
        tableColumns: [
          {
            title: '图片',
            dataIndex: 'img',
            width: 60,
          },
          {
            title: '产品名称',
            dataIndex: 'productName',
            width: 120,
          },
          {
            title: 'SKU',
            dataIndex: 'ssku',
            width: 140,
          },
          {
            title: '经销商SKU',
            dataIndex: 'sku',
            width: 140,
          },
          {
            title: '期望交期',
            dataIndex: 'gmtPlanDelivery',
            width: 140,
          },
          {
            title: '采购数',
            dataIndex: 'purchaseAmt',
            width: 70,
          },
          {
            title: '未交货',
            dataIndex: 'purchaseDeliveryStayAmt',
            width: 70,
          },
          {
            title: '本次交货',
            dataIndex: 'deliveryAmt',
            width: 70,
          },
          {
            title: '税率',
            dataIndex: 'rate',
            width: 60,
          },
          {
            title: '含税单价',
            dataIndex: 'price',
            width: 80,
          },
          {
            title: '库存单价',
            dataIndex: 'deliveryInventoryPrice',
            width: 80,
          },
          {
            title: '库存成本',
            dataIndex: 'deliveryInventoryValue',
            width: 80,
          },
        ],
        expandable: {
          title: '',
          defaultExpandAllRows: true,
          expandedRowKeys: [],
          width: 10,
        },
        tableList: [],
      })

      const open = () => {
        getWareHouseList()
        getDetail()
      }

      const getDetail = async () => {
        const res: any = await getSupplierDeliveryInfo({ id: props.list[0].id })
        let obj = res?.data || {}
        data.tableList = [obj]
        data.expandable.expandedRowKeys = data.tableList.map((el: any) => el.id)
        data.tableList.forEach((e: any) => {
          let arr = e.billItems.map((el: any) => {
            el.billId == e.billNo
            return el
          })
          data.itemList = [...data.itemList, ...arr]
        })
      }

      const handleOk = async () => {
        let params = {
          ids: [data.tableList[0].id],
        }
        data.loading = true
        await outboundSupplierDeliveryOrder(params)
        data.loading = false
        Message.success('出库成功')
        emit('save')
      }
      const handleCancel = () => {
        visible.value = false
      }

      const getWareHouseList = async () => {
        const res = await findWarehouseListByParam()
        let arr = res?.data
        data.houseList = arr
      }

      // 合并单元格
      const spanMethodAll = (option: any) => {
        let { column } = option
        if (column.dataIndex === 'img') {
          return { rowspan: 1, colspan: 12 }
        }
      }

      const summary = () => {
        let purchaseAmt = 0
        let deliveryDiffAmt = 0
        let deliveryAmt = 0
        let deliveryStayAmt = 0
        let deliveryInventoryValue = 0

        data.itemList.forEach((e: any) => {
          purchaseAmt += e.purchaseAmt || 0
          deliveryDiffAmt += e.deliveryDiffAmt || 0
          deliveryAmt += e.deliveryAmt || 0
          deliveryStayAmt += e.deliveryStayAmt || 0
          deliveryInventoryValue += e.deliveryInventoryValue || 0
        })

        return [
          {
            sku: '合计',
            purchaseAmt,
            deliveryDiffAmt,
            deliveryAmt,
            deliveryStayAmt,
            deliveryInventoryValue: `￥${deliveryInventoryValue}`,
          },
        ]
      }

      const toCheckDay = (time: any) => {
        let date = new Date(time).valueOf() + 24 * 60 * 60 * 1000
        let newDate = new Date().valueOf()
        let timeStr = date - newDate
        if (timeStr < 0) {
          let daty = Math.abs(timeStr) / (24 * 60 * 60 * 1000)
          return {
            type: false,
            day: Math.ceil(daty),
          }
        } else {
          let daty = Math.abs(timeStr) / (24 * 60 * 60 * 1000)
          return {
            type: true,
            day: Math.ceil(daty),
          }
        }
      }

      return {
        ...(toRefs(data) as any),
        visible,
        open,
        handleOk,
        handleCancel,
        formRef,
        spanMethodAll,
        summary,
        toCheckDay,
      }
    },
  })
</script>

<style lang="less" scoped>
  .table {
    width: 100%;

    :deep(.arco-table-td) {
      background-color: var(--color-fill-1);
    }
    :deep(.arco-table-tr-expand) {
      .arco-table-cell {
        padding: 0;
      }
      .arco-table {
        margin: 0 !important;
        .arco-table-td {
          border-bottom: 1px solid var(--color-neutral-3);
        }
      }
      background-color: #fff !important;
    }
    :deep(.child-row) {
      .arco-table-cell {
        padding: 2px 8px;
      }
    }
    :deep(.arco-table-tr-expand .arco-table-td) {
      background-color: #fff !important;
      border-bottom: none;
    }
    :deep(.arco-table-tr-expand tr:hover .arco-table-td) {
      background-color: var(--color-fill-1) !important;
    }
    :deep(.arco-table-expand .arco-table-cell) {
      display: none;
    }
    :deep(.arco-tabs-nav-tab) {
      background-color: #fff;
    }
  }

  .text-desc {
    font-size: 12px;
    margin-left: 10px;
    color: #7f7f7f;
  }

  .arco-col {
    margin-bottom: 5px;
  }

  .detail-item {
    display: flex;

    .label {
      width: 80px;
      text-align: right;
    }
    .value {
      flex: 1;
    }
  }
</style>
